// Copyright 2012 Google Inc. All Rights Reserved.

package com.google.appengine.preferencessync.adapter;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

/**
 * Service for Sync Adapter.
 */
public abstract class AbstractSyncablePrefsService extends Service {

  /**
   * Sync response.
   */
  public static class SyncResponse {
    private final String responseStr;
    private final boolean conflict;
    private final boolean error;

    /**
     * Constructor for the response.
     *
     * @param responseStr
     * @param conflict
     * @param error
     */
    public SyncResponse(String responseStr, boolean conflict, boolean error) {
      this.responseStr = responseStr;
      this.conflict = conflict;
      this.error = error;
    }

    /**
     * @return the responseStr
     */
    public String getResponseStr() {
      return responseStr;
    }

    /**
     * @return the hasConflict
     */
    public boolean hasConflict() {
      return conflict;
    }

    /**
     * @return the hasError
     */
    public boolean hasError() {
      return error;
    }
  }

  /**
   * Request processor for sending send request to the server.
   */
  public static class RequestProcessor {
    AbstractSyncablePrefsService parent;

    public RequestProcessor(AbstractSyncablePrefsService parent) {
      this.parent = parent;
    }

    public SyncResponse getResponse(String url, String reqType, String payload) throws Exception {
      return parent.getResponse(url, reqType, payload);
    }
  }

  private static SyncableSharedPreferencesAdapter adapter = null;

  @Override
  public void onCreate() {
    synchronized (SyncableSharedPreferencesAdapter.class) {
      if (adapter == null) {
        adapter = new SyncableSharedPreferencesAdapter(
            new RequestProcessor(this), getApplicationContext(), true);
      }
    }
  }

  @Override
  public IBinder onBind(Intent arg0) {
    return adapter.getSyncAdapterBinder();
  }

  /**
   * This function is overloaded in the user project. The user in his project has to override this
   * class and has to implement client response. In reality GPE generates the subclass for the user
   * and user will not have to write any code. This should be able to handle null urls. Expected
   * behaviour would be to call the generate cloud endpoint utils class to get the url.
   *
   * @param url url at which client calls the server.
   * @param reqtype The type of request.
   * @param payload The data assosiate with the request.
   * @return {@link SyncResponse} Response of the client.
   * @throws Exception
   */
  protected abstract SyncResponse getResponse(String url, String reqtype, String payload)
      throws Exception;
}
